package com.dx.financehy.http;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * @描述： 请求配置的公共
 * @作者：CLD
 * @创建时间：2020-10-18 00:25
 * </pre>
 **/
public class HttpRequestConfig {
    /**
     * 返回默认的类容类型【application/json】
     *
     * @return
     */
    protected static String getDefaultContentType() {
        return HttpConstants.CONTENT_TYPE_JSON;
    }

    /**
     * 设置默认的content-type: application/json
     */
    protected static void setContentTypeApplicationJson(HttpRequestBase httpBase) {
        httpBase.setHeader(HttpConstants.CONTENT_TYPE, HttpConstants.CONTENT_TYPE_JSON);
    }

    /**
     * 设置content-Type
     */
    protected static void setContentType(HttpRequestBase httpBase, String contentType) {
        httpBase.setHeader(HttpConstants.CONTENT_TYPE, contentType);
    }

    /**
     * 设置json请求体
     */
    protected static void setHttpBody(HttpEntityEnclosingRequestBase httpRequest, String body) {
        if (StrUtil.isBlank(body)) {
            return;
        }
        StringEntity entity = new StringEntity(body, HttpConstants.CHARSET_UTF_8);
        entity.setContentEncoding(HttpConstants.CHARSET_UTF_8);
        entity.setContentType(HttpConstants.CHARSET_UTF_8);
        httpRequest.setEntity(entity);
    }

    /**
     * 设置form请求体
     *
     * @param httpRequest
     * @param mapParam
     * @throws UnsupportedEncodingException
     */
    protected static void setHttpBody(HttpEntityEnclosingRequestBase httpRequest, Map<String, Object> mapParam) throws UnsupportedEncodingException {
        if (CollUtil.isEmpty(mapParam)) {
            return;
        }
        List<NameValuePair> list = new ArrayList<>();
        for (Map.Entry<String, Object> entry : mapParam.entrySet()) {
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
        }
        // 构造from表单对象
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "UTF-8");
        // 把表单放到post里
        httpRequest.setEntity(urlEncodedFormEntity);
    }

    /**
     * 设置头部参数
     *
     * @param httpBase
     * @param map
     */
    protected static void setHeader(HttpRequestBase httpBase, Map<String, String> map) {
        if (map == null || map.size() == 0) {
            return;
        }
        for (String item : map.keySet()) {
            httpBase.setHeader(item, map.get(item));
        }
    }

}
